
require "crc"

module(..., package.seeall)

local logtag = "automic1"
local cid, uid = 3, 3 -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local status,isLogin = 0,false
function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    -- 如果设置是本协议
    if udtu and tonumber(udtu.ntype) == 2 then 
        sys.taskInit(init) 
        -- sys.taskInit(test)
    end
end
function test()
    local val=10
    while true do
        usrdata.update({val,10})
        lcd.LCD_DATA[3] = 'sum:' .. val..":".."10"
        sys.wait(5000)
        val = val+1
    end
end
local function getLogin()
    -- login  @@40615131498IP:127.0.0.1##
    --        RX:+LANDSHA(服务器日期yymmddhhmmss)
    return "@@"..udtu.nsn.."IP:111.111.0.1##" -- 登录数据
end
local function sendHB()
    sys.publish("NET_SENT_RDY_" .. cid, "HB") -- 使用登陆代替心跳
    status = 2
end
local function login()
    sys.publish("NET_SENT_RDY_" .. cid, getLogin()) 
    status = 0
end
function process(d, status)
    if (status == 0 and d:sub(1, 8) == "+LANDSHA") then
        sys.publish("NET_SENT_RDY_1", udtu.nsn.." automic v1 LOGIN OK")
        isLogin = true
        update() --登录成功上报一次
    elseif (status == 1 and d:sub(1, 8) == "+LANDSHA") then
        sys.publish("NET_SENT_RDY_1", udtu.nsn.." automic v1 UPDATA OK")
        usrdata.IS_UP_OK_3 = true
        lcd.USR_STATUS = ' UPOK3'
        if usrdata.IS_UP_OK_1 then sys.publish("RTU_POWER_OFF") end
    else
        if d:byte(12) == 205 then update() end --召测
    end
end
local function valToBCD(v,len)
    if v < 0 then v = 0 end 
    return string.format("%0"..len.."d", math.floor(v))
end
function update()
    -- 等待读取数据
    local isOK, data = sys.waitUntil("USRDATA_UPDATE", 30 * 1000)
    usrdata.IS_UP_OK_3 = false
    local dd = data or usrdata.getVal()
    --68181868 010101010101 80CD 00 00000000 00000018 0b01180000000aad16
    if not dd or not dd.val or not dd.val[1] then
        log.error(logtag,"没有获取到设备数据，放弃上传")
        return
    end
    local sumv = tonumber(dd.val[1]) --累计
    local intv = tonumber(dd.val[2] or 0) --瞬时
    local crcData = udtu.dsn .."80CD0000002022"..valToBCD(sumv,8)..valToBCD(intv,4).."0000000000"
    local crcsum = string.checkSum(crcData:fromHex(),1)
    local dataHex = "68181868" .. crcData .. string.format("%02X",crcsum) .. "16"
    sys.publish("NET_SENT_RDY_" .. cid, dataHex:fromHex())
    log.warn(logtag,"socket send update:"..dataHex)
    status=1
end
function init()
    sys.subscribe("DTU_ALARM_ON", function() sys.taskInit(update) end)--在实时在线模式时触发
    cid = (cid or 3) -- 网络通道id，对应uartid
    while true do
        isLogin = false
        while not socket.isReady() or not create.getDatalink(cid) do -- 
            log.warn(logtag, "等待net[" .. cid .. "] connect...")
            sys.wait(1000)
        end
        login()
        while create.getDatalink(cid) do
            -- 等待有网络下发数据，或者到指定的上报时间间隔
            local result, id, data = sys.waitUntil("NET_RECV_WAIT_" .. cid, (tonumber(dtu.conf[cid][3]) or 180) * 1000)
            -- result, id, data = sys.waitUntil("NET_RECV_WAIT_" .. cid, 5 * 1000)
            -- 网络下发命令
            if result then
                if data then
                    log.warn(logtag, string.format("收到网络[%s]数据[status:%s]:%s", id, status, data:toHex()))
                    process(data, status)
                end
            else -- 超时(已到指定的时间间隔)
                log.warn(logtag, "发送心跳")
                sendHB()
            end
            if not isLogin then break end
        end
    end
end

